#include <iostream>
#include <variant>
#include <fstream>

enum class ErrorCode
{
    None = 0, 
    NotFound = 1,
    NoAccess = 2
};

std::variant<std::string, ErrorCode> ReadFileAsString(const std::string& filepath)
{
    std::ifstream stream(filepath);
    if(stream)
    { 

        if(stream.peek() == std::ifstream::traits_type::eof() )
           return ErrorCode::None;

        //read file
        std::string result;
        //stream >> result; // string类型读取，每次以\0结束

        std::string line;
        while(std::getline(stream, line) )
        {
            result += line;
        }  

        stream.close();
        return result;
    }
     
    return ErrorCode::NotFound; 
} 

int main()
{
    std::variant<std::string, ErrorCode> filedata = ReadFileAsString("data.txt");
    if(auto value = std::get_if<std::string>(&filedata))
    {
        std::string &v = *value;
        std::cout << " read data.txt file: " << v << std::endl;
    }
    else
    {
        //error
        //std::cout << std::get_if<ErrorCode>(&filedata) << std::endl; 
        std::cout << static_cast<int>(std::get<ErrorCode>(filedata)) << std::endl;
        if(std::get<ErrorCode>(filedata) == ErrorCode::None)
            std::cout << "file is empty!" << std::endl;

        if(std::get<ErrorCode>(filedata) == ErrorCode::NotFound)
            std::cout << "file is not existed!" << std::endl;  
    }

    std::variant<std::string, int> data; //一次只能赋值一次
    std::cout << sizeof(int) << std::endl; //4
    std::cout << sizeof(std::string) << std::endl; // 24
    std::cout << sizeof(data) << std::endl; // 32
    
    data = "caoxiansheng"; 
    std::cout << std::get<std::string>(data) << "\n";
    //判断的方式,std::get_if返回指针
    if(auto value = std::get_if<std::string>(&data))
    {
        std::string& v = *value;
        std::cout << "std::get_if<std::string>: " << v << std::endl;
    }
    else
    {

    }
    data = 2;
    std::cout << std::get<int>(data) << std::endl;

}
